package com.atguigu.gmall.common.service;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.bean.GmallCorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class RabbitService {


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 消息发送封装-延迟消息
     * @param exchange
     * @param routingKey
     * @param message
     * @param delayTime
     * @return
     */
    public boolean sendMessaged(String exchange,String routingKey,Object message,int  delayTime){

        //封装消息实体对象
        //封装消息实体对象
        GmallCorrelationData correlationData=new GmallCorrelationData();
        //设置id
        String correlationId = UUID.randomUUID().toString().replaceAll("-", "");
        correlationData.setId(correlationId);
        //设置交换机
        correlationData.setExchange(exchange);
        //设置routingKey
        correlationData.setRoutingKey(routingKey);
        //设置消息
        correlationData.setMessage(message);
        //设置超时时间
        correlationData.setDelayTime(delayTime);
        //设置是否为延迟
        correlationData.setDelay(true);

        //存储到redis
        redisTemplate.opsForValue().set(correlationId, JSON.toJSONString(correlationData),10, TimeUnit.MINUTES);


        //发送延迟消息
        rabbitTemplate.convertAndSend(exchange,routingKey,message,message1 -> {

            //设置延迟时间
            message1.getMessageProperties().setDelay(delayTime*1000);


            return message1;
        },correlationData);

        return true;


    }

    /**
     * 消息发送封装
     * @param exchange
     * @param routingKey
     * @param message
     * @return
     */
    public boolean sendMessaged(String exchange,String routingKey,Object message){


        //封装消息实体对象
        GmallCorrelationData correlationData=new GmallCorrelationData();
        //设置id
        String correlationId = UUID.randomUUID().toString().replaceAll("-", "");
        correlationData.setId(correlationId);
        //设置交换机
        correlationData.setExchange(exchange);
        //设置routingKey
        correlationData.setRoutingKey(routingKey);
        //设置消息
        correlationData.setMessage(message);

        //存储到redis
        redisTemplate.opsForValue().set(correlationId, JSON.toJSONString(correlationData),10, TimeUnit.MINUTES);

        //发送消息
        rabbitTemplate.convertAndSend(exchange,routingKey,message,correlationData);

        //发送消息
//        rabbitTemplate.convertAndSend(exchange,routingKey,message);


        return true;
    }



}
